﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using MiniFox.Log;
using MiniFox.Web.Configurations;
using System.Net.Mime;

namespace MiniFox.Web.AppStarting
{
    /// <summary>
    /// 
    /// </summary>
    internal class RegisterStaticResource : HttpStartBase
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="hostEnvironment"></param>
        /// <param name="webConfiguration"></param>
        public RegisterStaticResource(IConfiguration configuration, IWebHostEnvironment hostEnvironment, WebConfiguration webConfiguration) : base(configuration, hostEnvironment, webConfiguration)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        public override void OnApplicationConfiguring(IApplicationBuilder app)
        {
            if (this.WebConfiguration.ServerMode == ServerMode.WebApi)
                return;

            app.UseStaticFiles();
            foreach(var setting in this.WebConfiguration.StaticResources)
            {
                try
                {
                    FileServerOptions options = new();
                    options.DefaultFilesOptions.DefaultFileNames.Clear();
                    options.DefaultFilesOptions.FileProvider = new PhysicalFileProvider(Path.Combine(this.Environment.WebRootPath, setting.FolderName));
                    options.DefaultFilesOptions.RequestPath = setting.RequestPath;
                    options.DefaultFilesOptions.DefaultFileNames.Add(setting.DefaultFile);
                    options.StaticFileOptions.ServeUnknownFileTypes = true;
                    options.StaticFileOptions.DefaultContentType = MediaTypeNames.Application.Octet;
                    app.UseFileServer(options);
                }
                catch (Exception e)
                {
                    this.Logger.WriteError(new DefaultLogContent
                    {
                        Message = e.Message,
                        Exception = e
                    });
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        public override void OnServicesConfiguring(IServiceCollection services)
        {
        }
    }

}
